<?php
namespace app\common;

use Support\exception\NotFoundException;
use support\Log;
use Throwable;
use Webman\Exception\ExceptionHandlerInterface;
use Webman\Http\Request;
use Webman\Http\Response;

class CustomExceptionHandler implements ExceptionHandlerInterface
{

    public function report(Throwable $exception)
    {
        // 记录异常日志
        Log::error($exception);
    }

    /**
     * 渲染异常响应
     * @param Request $request 请求对象
     * @param Throwable $exception 异常对象
     * @return Response 响应对象
     */
    public function render(Request $request, Throwable $exception): Response
    {

        // 默认错误码
        $code = $exception->getCode() ?: 500;
        // 默认错误信息
        $message = $exception->getMessage() ?: '服务器内部错误';

        // 可根据不同异常类型定制错误信息和错误码
        if ($exception instanceof \InvalidArgumentException) {
            $code    = 400;
            $message = '参数错误: ' . $message;
        } else if ($exception instanceof NotFoundException) {
            $code    = 404;
            $message = '未找到资源';
        }

        // 返回统一格式的 JSON 响应
        return json([
            'code' => $code,
            'msg'  => $message,
        ]);
    }
}
